
var behaviorsbasiclist = require('../../../behavior/basiclist')
var addrbill = require('../../../../sys/sys_addr.js')
var clubaddrbill = require('../../../../model/shop_clubaddr.js')
Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  behaviors: [behaviorsbasiclist],
  /**
   * 组件的属性列表
   */
  properties: {
    shopaddr: {
      type: Object,
      value: null
    },
    delivery_config: {
      type: Object,
      value: null
    },
    mode: {
      type: Number,
      default: 2
    },
    themcolor: {
      type: Object,
      default: {}
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    pagelist: [],
    isshow: false,
    op: "",
    navCur: 0,
    modellist: [],
    CustomBar: 0,
    clubinfo: null,
    noheadformshow: false,
    selectaddr:null,
    cshoptype:"1"
  },

  ready() {


    var app = getApp();
    this.setData({ CustomBar: app.globalData.CustomBar })
    this.data.actbill = addrbill
  },
  /**
   * 组件的方法列表
   */
  methods: {
    cshoptypechange(ev){    
      this.setData({cshoptype:ev.detail})

    },
    set_init(clubinfo,useraddr) {
      this.setData({ isshow: true, clubinfo,selectaddr:useraddr })
      var arrwhere = {}
      if (clubinfo) {
        arrwhere["lat"] = clubinfo["lat"]
        arrwhere["lng"] = clubinfo["lng"]
      }
      arrwhere["limit"] = 1000
      var that = this;
      this.getpagelist(1, arrwhere, false).then(function (reslut) {
        that.dealmodellist(reslut)

      });
    },
    xcshow(navCur) {
      this.setData({ isshow: true, navCur })
      this.getpagelist(1);
    },
    Backfunc() {
      this.setData({ isshow: false })
    },
    hideform() {
      this.setData({ op: "" })
    },
    dealmodellist(reslut) {
      var clubinfo = this.data.clubinfo
      if (reslut["status"] != 1) {

        return;
      }
      var pagelist = reslut["obj"]["pagelist"];
      if(pagelist){
        var ilen = pagelist.length;


        if (clubinfo && ilen > 0) {
          var app = getApp();
          for (var i = 0; i < ilen; i++) {
            var selectaddr = pagelist[i]
            if (selectaddr.lng) {
              pagelist[i]["distance"] = app.toolv2.distanceByLnglat(selectaddr.lng, selectaddr.lat, clubinfo.lng, clubinfo.lat)
            }
          }
          reslut["obj"]["pagelist"] = pagelist.sort(function (a, b) {
            if (!a.distance) {
              return -1
            }
            else {
              a.distance.val - b.distance.val
            }
          })
  
  
        }
        if (ilen < 1) {
          reslut["obj"]["noheadformshow"] = true
          reslut["obj"]["op"]="add";
          
        }
        this.setData(reslut["obj"])
      }
      
    },

    selecteditem(e) {
      var app =getApp();
      var that =this;
      var dataset = e.currentTarget.dataset;
      var selectaddr = this.data.pagelist[dataset["idx"]];
      if (selectaddr.lat == 0 || !selectaddr.lat) {
        wx.showToast({
          title: '请先完善信息',
        })
        return;
      }

      var clubinfo=null
      
      if(this.data.cshoptype == 2){
        clubinfo= this.data.clubinfo
      }    
      
      var intracity = this.data.delivery_config.intracity;
      if(clubinfo){ 
        if (selectaddr["distance"].val - intracity["maxdistance"] > 0) {
          wx.showToast({
            title: '配送范围之外',
          })
          return;
        }
        that.selecteditemnext(clubinfo,selectaddr)
      }
      else{

        clubaddrbill.nearby(selectaddr.lat,selectaddr.lng,"",2).then(function(shopmodelres){
          if(shopmodelres["status"]!=1){
            wx.showToast({
              title: '没有设定商家',
            })
            return ;
          }
          else
          {
            clubinfo= shopmodelres["obj"]
          }

          selectaddr["distance"] = app.toolv2.distanceByLnglat(selectaddr.lng, selectaddr.lat, clubinfo.lng, clubinfo.lat,"",2)
          if (selectaddr["distance"].val - intracity["maxdistance"] > 0) {
            wx.showToast({
              title: '附近没有配送门店',
            })
            return;
          }

          that.selecteditemnext(clubinfo,selectaddr)       
        

          return ;

        })

        
      } 
      
    },

    selecteditemnext(clubinfo,selectaddr){
        var myEventDetail = {clubinfo,selectaddr} // detail对象，提供给事件监听函数
        var myEventOption = {} // 触发事件的选项
        this.triggerEvent("selectaddr", myEventDetail, myEventOption)
        this.setData({isshow:false})

    },
    addreditblack(e) {
     console.log("addreditblack")

     console.log(e)
      var addrmodel = e.detail
 
      var clubinfo= this.data.clubinfo
      if(clubinfo){
        var app =getApp();
        addrmodel["distance"] = app.toolv2.distanceByLnglat(addrmodel.lng, addrmodel.lat, clubinfo.lng, clubinfo.lat)        
      }

 
      var op = this.data.op;
      var that = this;
      var pagelist = that.data.pagelist
      if (op == "add") {
        pagelist.splice(0, 0, addrmodel)
      }
      if (addrmodel.isdefault == 1) {
        for (var a in pagelist) {
          if (pagelist[a].id != addrmodel.id) {
            pagelist[a].isdefault = -1
          }
        }
      }
      var updatemodel = {}
      updatemodel["pagelist"] = pagelist;
      updatemodel["op"] = "";
      if (this.data.noheadformshow == true) {
        updatemodel["noheadformshow"] = false
var that =this;
        setTimeout(function(){
          that.selecteditem({currentTarget:{dataset:{idx:0}}}) 
        },100)

      }    


      this.setData(updatemodel)

     

    },
    // 选择编辑导入增加地址
    optool(e) {
      var dataset = e.currentTarget.dataset;
      var addform = this.selectComponent("#addform");
      var idx = dataset.idx;
      var op = dataset.op
      var that = this;
      var updatemodel = {};
      switch (op) {
        case "del": {
          var model = this.data.pagelist[idx];
          var that = this;
          wx.showModal({
            title: '删除',
            content: "删除 " + model.name + "[" + model.phone + "]",
            showCancel: true,
            success(res) {
              if (res.confirm) {
                addrbill.del(model.id).then(function (vdata) {
                  if (vdata["status"] == 1) {
                    var pagelist = that.data.pagelist
                    pagelist.splice(idx, 1);
                    var updatemodel = { pagelist }
                    if (pagelist.length == 0) {
                      updatemodel["noheadformshow"] = true
                      updatemodel["op"] = "add"
                    }
                    that.setData(updatemodel);
                    wx.showToast({
                      title: '删除成功'
                    })
                  }
                })

              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          break;

        }
        case "edit": {
          addform.showop(dataset.op, this.data.pagelist[idx]);
          updatemodel["acteq"] = idx;
          updatemodel["op"] = op;
          this.setData(updatemodel)
          break;
        }
        case "add": {
          if (dataset.form == "choose") {
            wx.chooseAddress({
              success: function (res) {
                addform.showop(dataset.op, null, res);
                updatemodel["op"] = dataset.op;
                that.setData(updatemodel)
              }
            })
          }
          else {
            addform.showop(dataset.op, null);
            updatemodel["op"] = dataset.op;
            this.setData(updatemodel)
          }
          break;
        }
        case "setdefault": {
          var selectmodel = this.data.pagelist[idx];
          addrbill.setdefalut(selectmodel.id, -selectmodel.isdefault).then(function (params) {
            if (params["status"] == 1) {
            }
          })
          for (var ia in this.data.pagelist) {
            if (this.data.pagelist[ia].isdefault == 1) {
              updatemodel["pagelist.[" + ia + "].isdefault"] = -1;
              break;
            }
          }
          updatemodel["pagelist.[" + idx + "].isdefault"] = -selectmodel.isdefault;
          this.setData(updatemodel)
          break;
        }
        case "close": {
          this.setData({ op: "list" })
          break;
        }
      }
    },
    callphone(e){
      var phone=e.currentTarget.dataset.phone
      wx.makePhoneCall({
        phoneNumber: phone,
        success: function () {

        },
        fail: function () {

        }
      })
    }
  }
})
